<template>
  <div class="page_root" data-page-name="工单管理" data-page-identification="f_ut5tyy2zb0">
    <a-spin :spinning="spinning">
      <a-form ref="formRef" :model="formState" :layout="layout" :label-align="labelAlign" :label-col="labelCol" :wrapper-col="wrapperCol" :class="{'form_container': !isTablePage}">
        <div style="display: flex; flex-direction: column; width: 100%;">
          <a-form-item v-show="showState.vid_grpnxpuxa1_visible" name="z_jzr81kabpt" :class="{'form-item-antd_inputNumber_form_pc':true}">
            <template v-slot:label> 数字 </template>
            <!-- begin vid_grpnxpuxa1 数字_cq01hh33vv -->
            <a-input-number
              v-if="showState.vid_grpnxpuxa1_visible"
              ref="vid_grpnxpuxa1_ref"
              class="vid_grpnxpuxa1"
              :precision="0"
              addonBefore=""
              :allowClear="vid_grpnxpuxa1_props.allowClear"
              :required="vid_grpnxpuxa1_props.required"
              v-model:value="formState.z_jzr81kabpt"
              @update:value="() => z_jzr81kabpt_change?.forEach((func) => func())"
              :disabled="vid_grpnxpuxa1_props.disabled || isDetailType"
              :numberFormatType="vid_grpnxpuxa1_props.numberFormatType"
              :numberPrecision="vid_grpnxpuxa1_props.numberPrecision"
              :numberThousandthSeparator="vid_grpnxpuxa1_props.numberThousandthSeparator"
              :numberCurrencySymbol="vid_grpnxpuxa1_props.numberCurrencySymbol"
              :comparisonTips="vid_grpnxpuxa1_props.comparisonTips"
              :placeholder="vid_grpnxpuxa1_props.placeholder"
              :bordered="vid_grpnxpuxa1_props.bordered"
            >
            </a-input-number>
            <!-- end vid_grpnxpuxa1 数字_cq01hh33vv -->
          </a-form-item>
          <a-form-item v-show="showState.vid_zdhe0hcyjy_visible" name="n_sps00ub07i" :class="{'form-item-al_upload_form_pc':true}">
            <template v-slot:label> 文件上传 </template>
            <!-- begin vid_zdhe0hcyjy 文件上传_ycn5b1gtf7 -->
            <al-upload
              v-if="showState.vid_zdhe0hcyjy_visible"
              ref="vid_zdhe0hcyjy_ref"
              class="vid_zdhe0hcyjy"
              :name="vid_zdhe0hcyjy_props.name"
              :action="vid_zdhe0hcyjy_props.action"
              :uploadFile="vid_zdhe0hcyjy_props.uploadFile"
              :required="vid_zdhe0hcyjy_props.required"
              v-model:fileList="formState.n_sps00ub07i"
              @update:fileList="() => n_sps00ub07i_change?.forEach((func) => func())"
              :disabled="vid_zdhe0hcyjy_props.disabled || isDetailType"
              :placeholder="vid_zdhe0hcyjy_props.placeholder"
              :directory="vid_zdhe0hcyjy_props.directory"
              :multiple="vid_zdhe0hcyjy_props.multiple"
              :isSingle="vid_zdhe0hcyjy_props.isSingle"
              :showUploadList="vid_zdhe0hcyjy_props.showUploadList"
              :accept="vid_zdhe0hcyjy_props.accept"
              @uploadFailed="handle_vid_zdhe0hcyjy_uploadFailed"
              @uploadSuccess="handle_vid_zdhe0hcyjy_uploadSuccess"
            >
            </al-upload>
            <!-- end vid_zdhe0hcyjy 文件上传_ycn5b1gtf7 -->
          </a-form-item>
          <a-form-item v-show="showState.vid_2r5cbvskwg_visible" name="h_mt9qng2690" :class="{'form-item-antd_selectCheck_form_pc':true}">
            <template v-slot:label> 下拉复选框 </template>
            <!-- begin vid_2r5cbvskwg 下拉复选框_jngqkmciib -->
            <a-select
              v-if="showState.vid_2r5cbvskwg_visible"
              ref="vid_2r5cbvskwg_ref"
              class="vid_2r5cbvskwg"
              :mode="vid_2r5cbvskwg_props.mode"
              :autofocus="vid_2r5cbvskwg_props.autofocus"
              :allowClear="vid_2r5cbvskwg_props.allowClear"
              :multiple="vid_2r5cbvskwg_props.multiple"
              :required="vid_2r5cbvskwg_props.required"
              :showSearch="vid_2r5cbvskwg_props.showSearch"
              :filterOption="vid_2r5cbvskwg_props.filterOption"
              v-model:value="formState.h_mt9qng2690"
              @update:value="() => h_mt9qng2690_change?.forEach((func) => func())"
              :bordered="vid_2r5cbvskwg_props.bordered"
              :disabled="vid_2r5cbvskwg_props.disabled || isDetailType"
              :options="vid_2r5cbvskwg_options"
            >
            </a-select>
            <!-- end vid_2r5cbvskwg 下拉复选框_jngqkmciib -->
          </a-form-item>
          <a-form-item v-show="showState.vid_u4aiwklg75_visible" name="e_4xesktuffy" :class="{'form-item-antd_rangePicker_form_pc':true}">
            <template v-slot:label> 日期区间 </template>
            <!-- begin vid_u4aiwklg75 日期区间_b7sk7faie0 -->
            <a-range-picker
              v-if="showState.vid_u4aiwklg75_visible"
              ref="vid_u4aiwklg75_ref"
              class="vid_u4aiwklg75"
              :allowClear="vid_u4aiwklg75_props.allowClear"
              :valueFormat="vid_u4aiwklg75_props.valueFormat"
              :extraValueFormat="vid_u4aiwklg75_props.extraValueFormat"
              :required="vid_u4aiwklg75_props.required"
              v-model:value="formState.e_4xesktuffy"
              @update:value="() => e_4xesktuffy_change?.forEach((func) => func())"
              :disabled="vid_u4aiwklg75_props.disabled || isDetailType"
              :placeholder="vid_u4aiwklg75_props.placeholder"
              :showToday="vid_u4aiwklg75_props.showToday"
              :format="vid_u4aiwklg75_props.format"
              :picker="vid_u4aiwklg75_props.picker"
              :showTime="vid_u4aiwklg75_props.showTime"
            >
            </a-range-picker>
            <!-- end vid_u4aiwklg75 日期区间_b7sk7faie0 -->
          </a-form-item>
          <a-form-item v-show="showState.vid_9mh9wxzfl9_visible" name="c_t9ocrg4x5o" :class="{'form-item-antd_datePicker_form_pc':true}">
            <template v-slot:label> 日期时间 </template>
            <!-- begin vid_9mh9wxzfl9 日期_t0br9n9qzf -->
            <a-date-picker
              v-if="showState.vid_9mh9wxzfl9_visible"
              ref="vid_9mh9wxzfl9_ref"
              class="vid_9mh9wxzfl9"
              :allowClear="vid_9mh9wxzfl9_props.allowClear"
              :valueFormat="vid_9mh9wxzfl9_props.valueFormat"
              :extraValueFormat="vid_9mh9wxzfl9_props.extraValueFormat"
              :required="vid_9mh9wxzfl9_props.required"
              v-model:value="formState.c_t9ocrg4x5o"
              @update:value="() => c_t9ocrg4x5o_change?.forEach((func) => func())"
              :disabled="vid_9mh9wxzfl9_props.disabled || isDetailType"
              :placeholder="vid_9mh9wxzfl9_props.placeholder"
              :showToday="vid_9mh9wxzfl9_props.showToday"
              :format="vid_9mh9wxzfl9_props.format"
              :picker="vid_9mh9wxzfl9_props.picker"
              :showTime="vid_9mh9wxzfl9_props.showTime"
            >
            </a-date-picker>
            <!-- end vid_9mh9wxzfl9 日期_t0br9n9qzf -->
          </a-form-item>
          <a-form-item v-show="showState.vid_hjei4k4bgp_visible" name="h_rl39etvqxs" :class="{'form-item-antd_input_form_pc':true}">
            <template v-slot:label> 单行文本 </template>
            <!-- begin vid_hjei4k4bgp 单行文本_79sx0dj2l1 -->
            <a-input
              v-if="showState.vid_hjei4k4bgp_visible"
              ref="vid_hjei4k4bgp_ref"
              class="vid_hjei4k4bgp"
              :allowClear="vid_hjei4k4bgp_props.allowClear"
              :required="vid_hjei4k4bgp_props.required"
              v-model:value="formState.h_rl39etvqxs"
              @update:value="() => h_rl39etvqxs_change?.forEach((func) => func())"
              :disabled="vid_hjei4k4bgp_props.disabled || isDetailType"
              :comparisonTips="vid_hjei4k4bgp_props.comparisonTips"
              :placeholder="vid_hjei4k4bgp_props.placeholder"
              :bordered="vid_hjei4k4bgp_props.bordered"
            >
            </a-input>
            <!-- end vid_hjei4k4bgp 单行文本_79sx0dj2l1 -->
          </a-form-item>
        </div>
      </a-form>
      <div v-if="!isProcessState && !isTablePage" class="form-button">
        <a-button type="primary" :loading="submitLoading" @click="onSubmit">{{ props.editType === 'edit' ? '保存' :  isProcessForm ? '发起流程': '提交'}}</a-button>
      </div>
    </a-spin>
  </div>
</template>
<script setup>

  import {
    h, ref, reactive, toRaw, markRaw, watch, computed,
    onBeforeMount, onMounted, onBeforeUnmount, onUnmounted, onActivated, onDeactivated
  } from "vue";
  import { useRoute, useRouter } from 'vue-router';
  const router = useRouter();
  const route = useRoute();
  import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios';
  import { cloneDeep, localGet, merge, getDifferenceArray, traversalTreeStructure, checkCaseCondition, renderStringInTemplate,
    handleBreadcrumbJump, throttle, debounce, permission, getGridStyle, getCellRenderAble, formulaStrategy, getApplicationId, get as lodashGet } from '@/utils/index';
  import { isEqual, isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is';
  import { FormComponentKey } from '@/enums/componentKey';
  import dayjs from 'dayjs';
  import { getPagePcChartsDataSourceConvert } from '@/utils/chart';
  import { message, notification, Modal } from 'ant-design-vue';
  import { propertyFormatByNumber, propertyFormatByPercentage, propertyFormatByDate, accMul, exc } from '@/utils/format';
  import { checkCommonCondition, getResultByCurrentCommonCondition } from '@/utils/formCondition';
  import { FormFormat } from '@/utils/formFormat';
  import { customAddWaterMarkFunc, generateWaterMarkText } from '@/utils/addWaterMark';
  import hashSum from 'hash-sum';
  
  import UserTableRecords from '@/model/UserTableRecords';
  import { BroadcastMessage } from "@/utils/BroadcastMessage";
  import { parseJson } from "@/utils/common";
  


  
  
  const antPrefix = ref({"VITE_NODE":"Bate","VITE_PORT":"3100","VITE_GLOB_APP_TITLE":"天工傲","VITE_GLOB_APP_SHORT_NAME":"LCP","VITE_DROP_CONSOLE":"true","VITE_ANTD_PREFIX":"ant3","VITE_GLOB_API_URL":"","VITE_GLOB_UPLOAD_URL":"/upload","VITE_GLOB_API_URL_PREFIX":"","VITE_PUBLIC_PATH":"/","VITE_BUILD_COMPRESS":"gzip","BASE_URL":"/","MODE":"production","DEV":false,"PROD":true,"SSR":false}?.VITE_ANTD_PREFIX)
  

  const immediateWatch = (source, callback) => {
    watch(source, callback, {deep: true,immediate: true })
  }
  // ---------------------------- 事件定义 ----------------------------
  const emit = defineEmits(['saveSuccess'])
  // ============================ 事件定义 ============================

  // ---------------------------- 属性定义 ----------------------------
  const props = defineProps({
      id: {
          type: Number,
          required: false
      },
      editType: {
          type: String,
          required: false,
          default() {
              return 'create'
          }
      },
      isProcess: {
        type: Boolean,
        required: false,
        default() {
          return false;
        },
      },
      isTablePage: {
        type: Boolean,
        required: false,
        default() {
          return false;
        },
      },
      formData: {
          type: Object,
          required: false
      },
      // 关联数据
      associatedData: {
        type: Object,
        required: false,
      },
      // 关联表单
      associatedPageId: {
        type: Number,
        required: false
      },

  })

  const vid_grpnxpuxa1_props = reactive({
      allowClear: true,
      required: false,
      systemLabel: "数字",
      fieldKey: "z_jzr81kabpt",
      systemHideLabel: false,
      systemTooltip: undefined,
      systemFieldShow: true,
      disabled: false,
      systemDefaultValueType: "custom",
      systemValue: undefined,
      systemDataLinkage: undefined,
      systemCalculation: undefined,
      systemDataConnectorValue: undefined,
      systemCommitData: true,
      numberFormatType: "number",
      numberPrecision: 0,
      numberThousandthSeparator: false,
      numberCurrencySymbol: "",
      systemRules: undefined,
      comparisonTips: [],
      placeholder: "",
      bordered: true,
  })


  const vid_zdhe0hcyjy_props = reactive({
      name: "file",
      action: "/file-storage/api/v1/file/upload",
      uploadFile: (data) => request({
            url: '/file-storage/api/v1/file/upload',
            method:'POST',
            responseType:'blob',
            withCredentials: false,
            data,
            timeout: 360000,
            headers: {"Content-Type":"application/json"},
          }),
      required: false,
      systemLabel: "文件上传",
      fieldKey: "n_sps00ub07i",
      systemHideLabel: false,
      systemTooltip: undefined,
      systemFieldShow: true,
      disabled: false,
      systemDefaultValueType: "custom",
      systemFileList: [],
      systemDataLinkage: undefined,
      systemDataConnectorValue: undefined,
      systemCommitData: true,
      systemRules: undefined,
      placeholder: undefined,
      directory: false,
      multiple: false,
      isSingle: false,
      showUploadList: false,
      accept: "image/*",
  })


  const vid_2r5cbvskwg_props = reactive({
      mode: "multiple",
      autofocus: false,
      allowClear: true,
      multiple: true,
      required: false,
      showSearch: true,
      filterOption: (input, option) => {
      return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
      systemLabel: "下拉复选框",
      bordered: true,
      fieldKey: "h_mt9qng2690",
      systemHideLabel: false,
      systemTooltip: undefined,
      systemFieldShow: true,
      disabled: false,
      systemCommitData: true,
      systemDefaultValueType: "custom",
      systemValue: [],
      systemDataLinkage: undefined,
      systemCalculation: undefined,
      systemDataConnectorValue: undefined,
      systemRules: undefined,
      systemOptionType: "custom",
      systemOptions: [{"label":"选项1","selected":false,"value":"fku4bj9tfk"},{"label":"选项2","selected":false,"value":"t0ui05zfng"},{"label":"选项3","selected":false,"value":"6q5if0d7e4"}],
      systemAssociateOtherForms: undefined,
      systemDictionary: undefined,
      systemOptionDataLinkage: undefined,
      systemDataConnector: undefined,
  })


  const vid_u4aiwklg75_props = reactive({
      allowClear: true,
      valueFormat: "YYYY-MM-DD HH:mm:ss",
      extraValueFormat: 'YYYY-MM-DD HH:mm:ss',
      required: false,
      showTime: undefined,
      systemLabel: "日期区间",
      fieldKey: "e_4xesktuffy",
      systemHideLabel: false,
      systemTooltip: undefined,
      systemFieldShow: true,
      disabled: false,
      systemCommitData: true,
      systemDefaultValueType: "custom",
      systemValue: undefined,
      systemDataLinkage: undefined,
      systemCalculation: undefined,
      systemDataConnectorValue: undefined,
      systemRules: undefined,
      placeholder: ["开始时间","结束时间"],
      showToday: true,
      format: "YYYY-MM-DD HH:mm:ss",
      systemDefaultToday: true,
      systemCustomPicker: "date",
      picker: "date",
  })


  const vid_9mh9wxzfl9_props = reactive({
      allowClear: true,
      valueFormat: "YYYY-MM-DD HH:mm:ss",
      extraValueFormat: 'YYYY-MM-DD HH:mm:ss',
      required: false,
      showTime: undefined,
      systemLabel: "日期时间",
      fieldKey: "c_t9ocrg4x5o",
      systemHideLabel: false,
      systemTooltip: undefined,
      systemFieldShow: true,
      disabled: false,
      systemCommitData: true,
      systemDefaultValueType: "custom",
      systemValue: undefined,
      systemDataLinkage: undefined,
      systemCalculation: undefined,
      systemDataConnectorValue: undefined,
      systemRules: undefined,
      placeholder: "",
      showToday: true,
      format: "YYYY-MM-DD HH:mm:ss",
      systemDefaultToday: true,
      systemCustomPicker: "date",
      picker: "date",
  })


  const vid_hjei4k4bgp_props = reactive({
      allowClear: true,
      required: false,
      systemLabel: "单行文本",
      fieldKey: "h_rl39etvqxs",
      systemHideLabel: false,
      systemTooltip: undefined,
      systemFieldShow: true,
      disabled: false,
      systemDefaultValueType: "custom",
      systemValue: undefined,
      systemDataLinkage: undefined,
      systemCalculation: undefined,
      systemDataConnectorValue: undefined,
      systemCommitData: true,
      comparisonTips: [],
      systemRules: undefined,
      placeholder: "",
      bordered: true,
  })


  const componentPropsMap = {
      vid_grpnxpuxa1_props,
      vid_zdhe0hcyjy_props,
      vid_2r5cbvskwg_props,
      vid_u4aiwklg75_props,
      vid_9mh9wxzfl9_props,
      vid_hjei4k4bgp_props
  };

  // ============================ 属性定义 ============================

  // ---------------------------- 元素数据引用 ----------------------------
  // 表单数据加载状态
  const spinning = ref(true)
  // 表单的引用
  const formRef = ref()
  // 组件 数字_cq01hh33vv ref 的引用
  const vid_grpnxpuxa1_ref = ref(null);
  // 组件 文件上传_ycn5b1gtf7 ref 的引用
  const vid_zdhe0hcyjy_ref = ref(null);
  // 组件 下拉复选框_jngqkmciib ref 的引用
  const vid_2r5cbvskwg_ref = ref(null);
  // 组件 日期区间_b7sk7faie0 ref 的引用
  const vid_u4aiwklg75_ref = ref(null);
  // 组件 日期_t0br9n9qzf ref 的引用
  const vid_9mh9wxzfl9_ref = ref(null);
  // 组件 单行文本_79sx0dj2l1 ref 的引用
  const vid_hjei4k4bgp_ref = ref(null);
  // 动态key的map
  const fieldTypeMap = {"z_jzr81kabpt":"antd_inputNumber_form_pc","n_sps00ub07i":"al_upload_form_pc","h_mt9qng2690":"antd_selectCheck_form_pc","e_4xesktuffy":"antd_rangePicker_form_pc","c_t9ocrg4x5o":"antd_datePicker_form_pc","h_rl39etvqxs":"antd_input_form_pc"};
  // 动态key的map
  const refMap = {vid_grpnxpuxa1_ref,vid_zdhe0hcyjy_ref,vid_2r5cbvskwg_ref,vid_u4aiwklg75_ref,vid_9mh9wxzfl9_ref,vid_hjei4k4bgp_ref};
  const vid_2r5cbvskwg_options = ref(
  [{"label":"选项1","selected":false,"value":"fku4bj9tfk"},{"label":"选项2","selected":false,"value":"t0ui05zfng"},{"label":"选项3","selected":false,"value":"6q5if0d7e4"}]
  )

  const optionsRef = reactive({
      vid_2r5cbvskwg_options
  });

  const showState = reactive({
      vid_grpnxpuxa1_visible: true,
      vid_zdhe0hcyjy_visible: true,
      vid_2r5cbvskwg_visible: true,
      vid_u4aiwklg75_visible: true,
      vid_9mh9wxzfl9_visible: true,
      vid_hjei4k4bgp_visible: true,
  })
  // ============================ 元素数据引用 ============================

  // ---------------------------- 数据 ----------------------------
  const formName = '工单管理';
  const applicationId = getApplicationId();
  const pageId = 3000000724;
  const locationOrigin = 'http://asa.mdiri.com';
  // 当前表单是否绑定了流程
  const isProcessForm = ref(false);
  const submitLoading = ref(false);
  // 当前表单详情数据
  const formDetailData = ref({});
  const subFormMap = {}
  const userInfo = localGet('al__USER_INFO')
  const labelCol = {}
  const wrapperCol = {}
  // horizontal | vertical
  const layout = "vertical"
  // left | right
  const labelAlign = "left"
  const formState = reactive({
      z_jzr81kabpt: '',
      n_sps00ub07i: [],
      h_mt9qng2690: [],
      e_4xesktuffy: [dayjs().format(vid_u4aiwklg75_props.valueFormat),dayjs().format(vid_u4aiwklg75_props.valueFormat)],
      c_t9ocrg4x5o: dayjs().format(vid_9mh9wxzfl9_props.valueFormat),
      h_rl39etvqxs: '',
  })

  const fieldKeyMap = {"z_jzr81kabpt":"vid_grpnxpuxa1","n_sps00ub07i":"vid_zdhe0hcyjy","h_mt9qng2690":"vid_2r5cbvskwg","e_4xesktuffy":"vid_u4aiwklg75","c_t9ocrg4x5o":"vid_9mh9wxzfl9","h_rl39etvqxs":"vid_hjei4k4bgp"};
  // 单选按钮组其他选项输入值
  const radioOtherValueMap = reactive({
  })


  const rules = {
  }
  const formFormat = new FormFormat(fieldTypeMap, fieldKeyMap, optionsRef, componentPropsMap)
  // ============================ 数据 ============================

  // ---------------------------- 页面数据 ----------------------------

  // ============================ 页面数据 ============================

  // ---------------------------- 方法 ----------------------------

  // 当前editType是否是详情状态
  const isDetailType = computed(() => {
    return props.editType === 'detail'
  })
  // 处理校验
  const setSubFormName =(parentInfo, name)=>{
    return [parentInfo.parents, parentInfo.index, name];
  }
  // 处理提交校验
  const handleSubmitVerify = async function(){
    // 引入公式校验的参数
    const submitRulesMap = [];
    // 校验公式计算结果
    let ruleVerifyResult = submitRulesMap.every(result => {
      return result();
    });
    // 如果未通过通过公式，不再进行联合唯一校验
    if(!ruleVerifyResult){
      return ruleVerifyResult;
    }
    // 通过公式校验后，进行联合唯一校验
    let uniqueKeyVerifyResult = true;
    const submitUniqueKeyResponse = await Promise.all([]);
    const submitUniqueKeyTipsMap = [];
    const submitUniqueShowStateMap = [];
    submitUniqueKeyResponse.forEach((item, index) => {
      // 唯一校验中所有组件都是隐藏的，不进行校验
      const showState = submitUniqueShowStateMap[index].every((state) => !state)
      if (item.data && !showState) { // 重复了
        uniqueKeyVerifyResult = false; // 重置标志位
        message.error(submitUniqueKeyTipsMap[index]); // 弹出错误提示
      }
    });

    return uniqueKeyVerifyResult;
  };

  // 重置子表单
  const resetSubform = () =>{
    Object.keys(subFormMap).forEach(key=>{
      // 通过fieldKey找到ref
      if(fieldKeyMap[key] && refMap[fieldKeyMap[key]+'_ref']){
        refMap[fieldKeyMap[key]+'_ref']?.value?.reset && refMap[fieldKeyMap[key]+'_ref'].value.reset();
      }
    });
  }
  // 重置表单
  const resetForm = () => {
    try {
      formRef.value?.resetFields && formRef.value.resetFields();
      // 重置图片H5上传的数据定时器


        // 主动调用子表单方法，重置数据
        resetSubform();
    } catch (error) {
      console.log('resetForm:', error)
      // 主动调用子表单方法，重置数据
      resetSubform();
    }
  };
  // 清除缓存
  const clearCache = () => {
    localStorage.removeItem('from_cache_f_ut5tyy2zb0_' + props.editType);
  };
  // 获取提交参数
  const getParams = (formModal = toRaw(formState)) => {
    const bodyConfig = [];
    const childrenList = [];
    Object.keys(formModal).forEach(key => {
      // 是子表单
      if (subFormMap && subFormMap[key]) {
        if (!componentPropsMap[`${fieldKeyMap[key]}_props`]?.systemCommitData || !formModal[key]) {
          return;
        }
        formModal[key].forEach(subformItem => {
          const childrenListItem = {
            pageId: subFormMap[key],
            bodyConfig: [],
            childrenList: []
          };
          // 如果有子表单数据
          if (subformItem) {
            Object.keys(subformItem).forEach(childKey => {
              if (childKey === "id") {
                childrenListItem.id = subformItem[childKey];
              } else {
                if (!componentPropsMap[`${fieldKeyMap[childKey]}_props`]?.systemCommitData || childKey.endsWith('_options')) {
                  return;
                }
                // 子表单数据转成期望的格式
                childrenListItem.bodyConfig.push({
                  key: childKey,
                  value: formFormat.setMixedTypeValue(childKey, subformItem[childKey], componentPropsMap[`${fieldKeyMap[childKey]}_props`], handleFormHiddenFieldSetting(childKey, key), {isSubform: true, subformItemLable: subformItem[`${childKey}_label`] })
                });
                const formatValue = formFormat.setFormatMixedTypeValue(childKey, subformItem[childKey], componentPropsMap[`${fieldKeyMap[childKey]}_props`], handleFormHiddenFieldSetting(childKey, key));
                if (formatValue) {
                  childrenListItem.bodyConfig.push({
                    key: childKey + '_format',
                    value: formatValue,
                  });
                }
              }
            });
          }
          childrenList.push(childrenListItem);
        });
      } else if (JSON.stringify(formModal[key]) !== '[{}]') { // 舍弃空子表单提交
        if (!componentPropsMap[`${fieldKeyMap[key]}_props`]?.systemCommitData) {
          return;
        }
        bodyConfig.push({
          key,
          value: formFormat.setMixedTypeValue(key, formModal[key], componentPropsMap[`${fieldKeyMap[key]}_props`], handleFormHiddenFieldSetting(key))
        });
        // 提交格式化数据
        const formatValue = formFormat.setFormatMixedTypeValue(key, formModal[key], componentPropsMap[`${fieldKeyMap[key]}_props`], handleFormHiddenFieldSetting(key));
        if (formatValue) {
          bodyConfig.push({
            key: key + '_format',
            value: formatValue,
          });
        }
      }
    });
    return {
      pageId,
      applicationId,
      processInstanceName: formName,
      bodyConfig,
      // 处理子表单
      childrenList
    };
  };

  // 为了更好实现诸多需求，将提交校验逻辑，组装数据逻辑，调用接口逻辑进行解耦
  const handleSubmit = async (submitDataFn) => {
    const formModal = toRaw(formState);
    await formRef.value?.validateFields();
    const submitResult = await handleSubmitVerify();
    if(!submitResult){
      return;
    }
    if(props.editType === 'create') {
      const serialNumberIdComponentIdMap = {};
      const serialSubformMap = {}
      if (serialNumberIdComponentIdMap && Object.keys(serialNumberIdComponentIdMap).length > 0) {
        const apiList = []
        const res = await Promise.all(apiList)
        res.forEach(item => {
          item.data ??= []
          item.data.forEach((rule, index) => {
            // 子表单中的流水号
            if (serialSubformMap[rule.serialNumberId]) {
              const subformItemHeight = formState[serialSubformMap[rule.serialNumberId]].length
              // 获取当前流水号的所在的索引值
              const currentItemIndex = index % subformItemHeight
              const subformKey = serialSubformMap[rule.serialNumberId]
              const fieldKey = serialNumberIdComponentIdMap[rule.serialNumberId]
              formModal[subformKey][currentItemIndex][fieldKey] = rule.value
            } else {
              // 常规的流水号
              const fieldKey = serialNumberIdComponentIdMap[rule.serialNumberId]
              // 取出根据规则生成的流水号并赋值
              formModal[fieldKey] = rule.value
            }
          })
        })
      }
      const params = getParams(formModal);
      params.triggerAction = 'CREATE';
      submitDataFn(params, post);
    } else {
      const params = getParams(formModal);
      params.id = props.id;
      params.triggerAction = 'EDIT';
      params.pageDataIdList = [props.id];
      submitDataFn(params, put);
    }
  }
  // 处理表单提交逻辑
  const onSubmit = async function () {
    submitLoading.value = true;
    handleSubmit((params, requestMethod) => {
      requestMethod('/taishan-runtime/api/v4/page_data/'+pageId, params).then((res) => {
        if (res.status === 'success') {
          message.success("数据提交成功");
          resetForm();
          emit('saveSuccess');
          // 清除缓存
          clearCache();
        } else {
          message.error(res.errorMsg || "数据提交失败");
        }
      }).catch((error) => {
        message.error((error && error.message) || "数据提交失败");
      }).finally(() => {
        submitLoading.value = false;
      });
    }).finally(() => {
      submitLoading.value = false;
    });
  };
  const controlFormItemVisible = (fieldKey, visible) => {
      // 如果是子表单，获取实际字段
      const realFieldKey = fieldKey.indexOf('.') > -1 ? fieldKey.split('.').pop() : fieldKey
      const _fieldKey = realFieldKey.replace('_labels', '').replace('_begin', '').replace('_end', '')
      showState[`${fieldKeyMap[_fieldKey]}_visible`] = visible
  }

  const controlFormItemDisabled = (fieldKey, disabled) => {
      // 如果是子表单，获取实际字段
      const realFieldKey = fieldKey.indexOf('.') > -1 ? fieldKey.split('.').pop() : fieldKey
      const _fieldKey = realFieldKey.replace('_labels', '').replace('_begin', '').replace('_end', '')
      componentPropsMap[`${fieldKeyMap[_fieldKey]}_props`].disabled = disabled
  }
  // Expose部分函数供外包调用
  defineExpose({ formRef, formState, subFormMap, controlFormItemVisible, controlFormItemDisabled, getParams, handleSubmit, onSubmit, resetForm, clearCache });


  // ============================ 方法 ============================

  // ---------------------------- 生命周期 ----------------------------
  
    // 流程同意后，向上一层传递信息
    const channel = new BroadcastMessage();
    channel.subscribe((data) => {
        const { actions } = data || {};
        if (actions === "submit") {
            const formModal = toRaw(formState);
            channel.publish({ formData: JSON.stringify(getParams(formModal)) });
        }
    });

    // 获取上一层传递的数据
    const isProcessState = ref(false);
    const workflowState = ref();
    const workflowChannel = new BroadcastMessage("WORKFLOW");
    workflowChannel.publish({ status: "Ready" });
    workflowChannel.subscribe((data) => {
        isProcessState.value = props.isProcess || window.self !== window.parent;
        workflowState.value = parseJson(data.formData);

        const pageFieldIdList = parseJson(data.pageFieldIdList);
        pageFieldIdList &&
            pageFieldIdList.forEach((fieldState) => {
                controlFormItemVisible(fieldState.filedId, fieldState.visibilityFlag);
                controlFormItemDisabled(fieldState.filedId, !fieldState.editableFlag);
            });

        getPageInfo();
    });
    


    const getPageInfo = ()=>{
      const formDataDeal = {};
      
      const formData = workflowState?.value || {};
      if (!isEmpty(formData)) {
          formData.bodyConfig.forEach((item) => {
              formDataDeal[item.key] = item.value;
          });
          // 处理子表单数据
          if (subFormMap && formData.childrenList) {
              const pageIdKeyMap = {};
              Object.keys(subFormMap).forEach((key) => {
                  pageIdKeyMap[subFormMap[key]] = key;
              });
              formData.childrenList.forEach((item) => {
                  const fieldKey = pageIdKeyMap[item.pageId];
                  if (!fieldKey) {
                      return;
                  }
                  if (!formDataDeal[fieldKey]) {
                      formDataDeal[fieldKey] = [];
                  }
                  const subformItem = {};
                  item.bodyConfig.forEach((subItem) => {
                      subformItem[subItem.key] = subItem.value;
                  });
                  formDataDeal[fieldKey].push(subformItem);
              });
          }
      }
      

      if (!isEmpty(formDataDeal)) {
          // 如果通过postMessage传递进来信息
          Object.keys(formState).forEach((key) => {
              if (formDataDeal.hasOwnProperty(key)) {
                  const formatValue = formFormat.getSelfFormatValue(
                      key,
                      formDataDeal[key],
                      componentPropsMap[`${fieldKeyMap[key]}_props`]
                  );
                  let formatValueResult = formFormat.getMixedTypeValue(formatValue, key);
                  // if base is not Object and result is array with ONE item, set it to base value
                  if (
                      formatValueResult &&
                      isArray(formatValueResult) &&
                      formatValueResult.length === 1 &&
                      typeof formState[key] !== "object"
                  ) {
                      formatValueResult = formatValueResult[0];
                  }
                  // 如果是子表单且返回的数据为null，暂不使用提交的数据
                  if (subFormMap[key]) {
                      // 对子表单字段进行格式化赋值
                      if (formatValueResult && formatValueResult.length) {
                          const optionData = {};
                          Object.keys(formState[key][0]).forEach((subKey) => {
                              if (subKey.endsWith("_options")) {
                                  // 复制options数据
                                  optionData[subKey] = cloneDeep(formState[key][0][subKey]);
                              }
                          });
                          formState[key] = formatValueResult.map((item, index) => {
                              Object.keys(item).map((subKey) => {
                                  const formatValue = formFormat.getSelfFormatValue(
                                      subKey,
                                      item[subKey],
                                      componentPropsMap[`${fieldKeyMap[subKey]}_props`]
                                  );
                                  // 更新单选按钮组其他选项
                                  radioOtherValueMap[key]?.[0]?.hasOwnProperty(subKey) &&
                                      (item[`${subKey}_label`] = formFormat.getRadioOtherValue(
                                          item[subKey],
                                          subKey,
                                          optionsRef[`${fieldKeyMap[subKey]}_options`],
                                          `${fieldKeyMap[subKey]}_options`
                                      ));
                                  item[subKey] = formFormat.getMixedTypeValue(formatValue, subKey);
                              });
                              // TODO:Black_Magic_Mark 为了正确加载子表单里动态的选项
                              Object.keys(optionData).forEach((optionKey) => {
                                  setTimeout(() => {
                                      dataLinkageHandlerMap[`${optionKey.replace(/_options$/, "")}_DataLinkage`]?.(index);
                                  }, 0);
                              });
                              item = { ...item, ...optionData };
                              return item;
                          });
                      }
                  } else {
                      formState[key] = formatValueResult;
                      // 更新单选按钮组其他选项
                      radioOtherValueMap.hasOwnProperty(key) &&
                          (radioOtherValueMap[key] = formFormat.getRadioOtherValue(
                              formDataDeal[key],
                              key,
                              optionsRef[`${fieldKeyMap[key]}_options`],
                              `${fieldKeyMap[key]}_options`
                          ));
                  }
              }
          });
          spinning.value = false;
      } else if (props.editType === 'create') {
        // 根据表单编辑类型，加载数据
        const associatedDataConfirmMethods = []
        // 使用关联数据
        if(props.associatedData) {
          Object.keys(associatedDataConfirmMethodMap).forEach(id => {
            const [, pageId] = id.split('.');
            if(pageId == props.associatedPageId) {
              associatedDataConfirmMethods.push(associatedDataConfirmMethodMap[id])
            }
          })
          if(associatedDataConfirmMethods.length) {
            associatedDataConfirmMethods.forEach(method => method(null, props.associatedData))
          }
        }
        spinning.value = false
      } else if (props.formData) {
        Object.keys(formState).forEach(key => {
            if (props.formData.hasOwnProperty(key)) {
                const formatValue = formFormat.getSelfFormatValue(key, props.formData[key], componentPropsMap[`${fieldKeyMap[key]}_props`]);
                formState[key] = formFormat.getMixedTypeValue(formatValue, key)
            }
        })
        spinning.value = false
      } else {
          post('/taishan-runtime/api/v4/page_data/detail', {
              id: props.id,
              pageId: pageId,
              bodyConfig: [
                  {
                      key: ''
                  }
              ]
          }).then(resp => {
              const { data } = resp;
              if (data && data.dataList && data.dataList.length > 0) {
                  const result = data.dataList[0]
                  formDetailData.value = data.dataList[0]
                  Object.keys(formState).forEach(key => {
                      if (result.hasOwnProperty(key)) {
                        const formatValue = formFormat.getSelfFormatValue(key, result[key], componentPropsMap[`${fieldKeyMap[key]}_props`]);
                        const formatValueResult = formFormat.getMixedTypeValue(formatValue, key)
                        // 如果是子表单且返回的数据为null，暂不使用提交的数据
                        if(subFormMap[key]){
                          // 对子表单字段进行格式化赋值
                          if (formatValueResult && formatValueResult.length) {
                            const optionData = {};
                            Object.keys(formState[key][0]).forEach(subKey => {
                                if (subKey.endsWith('_options')) {
                                  // 复制options数据
                                  optionData[subKey] = cloneDeep(formState[key][0][subKey]);
                                }
                            })
                            formState[key] = formatValueResult.map((item, index) => {
                                Object.keys(item).map(subKey => {
                                  const formatValue = formFormat.getSelfFormatValue(subKey, item[subKey], componentPropsMap[`${fieldKeyMap[subKey]}_props`]);
                                  // 更新单选按钮组其他选项
                                  radioOtherValueMap[key]?.[0]?.hasOwnProperty(subKey) && (item[`${subKey}_label`] = formFormat.getRadioOtherValue(item[subKey], subKey, optionsRef[`${fieldKeyMap[subKey]}_options`], `${fieldKeyMap[subKey]}_options`))
                                  item[subKey] = formFormat.getMixedTypeValue(formatValue, subKey);
                                })
                                // TODO:Black_Magic_Mark 为了正确加载子表单里动态的选项
                                Object.keys(optionData).forEach(optionKey => {
                                  setTimeout(() => {
                                    dataLinkageHandlerMap[`${optionKey.replace(/_options$/, '')}_DataLinkage`]?.(index)
                                  }, 0);
                                })
                                item = { ...item, ...optionData }
                                return item;
                            })
                          }
                        } else {
                          formState[key] = formatValueResult
                          // 更新单选按钮组其他选项
                          radioOtherValueMap.hasOwnProperty(key) && (radioOtherValueMap[key] = formFormat.getRadioOtherValue(result[key], key, optionsRef[`${fieldKeyMap[key]}_options`], `${fieldKeyMap[key]}_options`))
                        }
                      }
                  })
              }
          }).finally(() => {
              spinning.value = false
          })
      }
    }

    watch(
      () => props.formData,
      () => {
        Object.keys(formState).forEach(key => {
          if (props.formData.hasOwnProperty(key)) {
              const formatValue = formFormat.getSelfFormatValue(key, props.formData[key], componentPropsMap[`${fieldKeyMap[key]}_props`]);
              formState[key] = formFormat.getMixedTypeValue(formatValue, key)
          }
      })
      }
    )
  onMounted(() => {


      getPageInfo();
      // 加载数据字典数据

      // 加载其他表单数据

      // 从接口加载某些数据

  })
  onUnmounted(() => {
    // 清除图片上传的轮询

  });

  // ============================ 生命周期 ============================

  // ---------------------------- 页面数据匹配Options ----------------------------

  // ============================ 页面数据匹配Options ============================

  // ---------------------------- 数据关联处理 ----------------------------

  const dataLinkageHandlerMap = {}






      const handleFormHiddenFieldSetting = (key, parentKey) => {
        // 先判断组件隐藏状态
        let componentShowState;
        if(parentKey) {
          // 只有父组件和子组件同时显示才显示
          componentShowState =  showState[`${fieldKeyMap[key]}_visible`] && showState[`${fieldKeyMap[parentKey]}_visible`]
        } else {
          componentShowState = showState[`${fieldKeyMap[key]}_visible`]
        }
        // 隐藏字段默认配置重新计算
        if('recalculate' === 'recalculate') {
          return true
        } else if('recalculate' === 'empty') {
          // 隐藏字段默认配置置空
          return componentShowState
        }
        return true
      }

  // ============================ 数据关联处理 ============================

  // ---------------------- 不同组件自定义的处理逻辑 ---------------------

  const associatedDataConfirmMethodMap = {
  }
  // ====================== 不同组件自定义的处理逻辑 ======================

  // ---------------------------- 组件事件处理方法 ----------------------------
  /**
  * 处理元素 文件上传 的 uploadFailed 事件
  */
  let handle_vid_zdhe0hcyjy_uploadFailed = async (...params) => {
  // 上传失败
  const [errorMsg = ''] = params;
  message.error('上传失败! ' + errorMsg);
  }
  /**
  * 处理元素 文件上传 的 uploadSuccess 事件
  */
  let handle_vid_zdhe0hcyjy_uploadSuccess = async (...params) => {
  // 上传成功
  message.success('上传成功!');
  }
  // ============================ 组件事件处理方法 ============================


  // ================================定制化逻辑========================================
</script>
<style lang="less" scoped>
  .page_root .form_container {
  height: calc(100% - 48px);
  overflow: auto;
  padding-top: 24px;
  padding-right: 24px;
  padding-left: 24px;
  }
  .page_root{
  width: 100%;
  height: 100%;
  overflow: auto;
  }
  .form_container {
  background-color:#FFFFFF;
  }
  .page_root {
      .form-button {
        text-align: left;
        height: 48px;
        padding: 8px 24px;
        box-shadow: 2px 0px 8px 0px rgba(0,0,0,0.15);
        z-index:1;
      }
      :deep(textarea){
        resize: none;
      }
      .subform-checkbox-select{
        :deep(.@{ant-prefix}-checkbox)
        {
          display: none;
        }
        :deep(.@{ant-prefix}-select-selection-item)
        {
          padding-left: 0;
        }
      }
      :deep(.al-subform-item) .form-item-antd_rangePicker_form_pc{
        min-width: 375px;
      }
      :deep(.@{ant-prefix}-spin-container)
      {
        height: 100%;
        display: flex;
        flex-direction: column;
      }
      & :deep(.@{ant-prefix}-spin-nested-loading){
        height: 100%;
      }
    }
  .truncate{
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  /* 标签页黑魔法 */
    :deep(.@{ant-prefix}-tabs-tabpane) {
        height: 100%;
    }
  .vid_grpnxpuxa1{
      max-width: 400px;
  }
  .vid_grpnxpuxa1{
      width:100%
  }

  .vid_2r5cbvskwg{
      max-width: 400px;
  }
  .vid_u4aiwklg75{
      max-width: 400px;
  }
  .vid_9mh9wxzfl9{
      max-width: 400px;
  }
  .vid_9mh9wxzfl9{
      width:100%
  }
  .vid_hjei4k4bgp{
      max-width: 400px;
  }
</style>